<template v-cloak>
	<view class="container position-relative w-100 h-100 overflow-hidden">
		<view class="tabbar">
			<view class="tab" :class="{active: activeTabIndex == index}" 
				v-for="(item, index) in tabs" :key="index" @tap="handleTab(index)">
				<view class="title">{{ item.title }}</view>
			</view>
		</view>
		<view v-if="!coupons.length" class="none"><image src="/static/images/empty.png" mode=""></image></view>
		<view class="flex-fill">
			<scroll-view scroll-y class="coupon-list">
				<view class="wrapper">
					<view :class="[(amount && parseFloat(item.satisfy_price) > parseFloat(amount)) ? 'coupon gray' : 'coupon']" v-for="(item, index) in coupons" :key="index">
						<view class="d-flex detail">
							<image :src="item.imageUrl" class="coupon-img"></image>
							<view class="flex-fill d-flex flex-column justify-content-between overflow-hidden">
								<view class="font-size-lg text-color-base text-truncate mb-10">{{ item.title }}</view>
								<view class="font-size-sm text-color-base">有效期至{{ item.etime }}</view>
							</view>
							<view class="use">
								<view :class="[activeBtn == index || item.id == scoupon.id ? 'activeBtn' : '' ,'btn']" @tap="handelUse(index, item)">
									<span>{{activeBtn == index || item.id == scoupon.id? '取消使用' : '立即使用'}}</span>
								</view>
								<view class="info" @tap="openDetailModal(item)">
									<span>使用说明</span>
								</view>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>

		<modal custom :show="detailModalVisible" @cancel="closeDetailModal" width="90%">
			<view class="modal-content">
				<view class="d-flex font-size-extra-lg text-color-base just-content-center mb-20">{{ coupon.title }}</view>
				<view class="d-flex font-size-sm text-color-base mb-20">
					有效期：{{getDifferDate(new Date(), coupon.etime, 1)}} 天
				</view>
				<pre class="pre-line font-size-sm text-color-assist mb-30">
					<jyf-parser ref="couponExplain"></jyf-parser>
				</pre>
				<view class="d-flex align-items-center just-content-center">
					<button type="primary" @tap="closeDetailModal" class="use-coupon-btn">知道了</button>
				</view>
			</view>
		</modal>
	</view>
</template>

<script>
import modal from '@/components/modal/modal'
import jyfParser from "@/components/jyf-parser/jyf-parser"

export default {
	components: {
		modal,
		jyfParser
	},
	data() {
		return {
			tabs: [
				{title: '全部', value: 'all'},
				{title: '满减券', value: '1'},
				{title: '抵用券', value: '2'}
			],
			activeTabIndex: '',
			coupons: [],
			detailModalVisible: false,
			coupon: {},
			amount:0,
			activeBtn:'false',
			scoupon:[]
		}
	},
	onLoad(option) {
		if (option.hasOwnProperty('amount')) {
			this.amount = option.amount
		}
	},
	onShow() {
		this.activeTabIndex = 0
		this.scoupon = uni.getStorageSync('coupon')
	},
	watch: {
		activeTabIndex: async function(val) {
			const type = this.tabs[val].value
			await this.getCoupons(type)
		}
	},
	methods: {
		handleTab(index) {
			this.activeTabIndex = index
		},
		async getCoupons(type) {
			//请求优惠券
			this.$http.get('/user/coupons', {}).then(res => {
				if(type == 'all') {
					this.coupons = res.data.data
				} else {
					this.coupons = res.data.data.filter(item => item.type == type)
				}
				
			}).catch(err => {
			
			})
			// const coupons = await this.$api('customerCoupons')
		},
		openDetailModal(coupon) {
			this.coupon = coupon
			this.$refs['couponExplain'].setContent(this.coupon.content || '')
			this.detailModalVisible = true
		},
		closeDetailModal() {
			this.detailModalVisible = false
			this.coupon = {}
		},
		useCoupon(index, coupon) {
			// 判断是否点击相同的优惠券
			if (this.scoupon) {
				// 点击过了
				if (this.scoupon.id == coupon.id) {
					this.activeBtn = 'false'
					uni.removeStorageSync('coupon')
					this.scoupon = []
					return uni.showToast({
						icon:'none',
						title:'取消成功'
					})
				}
			}
			// 满减券
			if(coupon.type == 1){
				// console.log(satisfy_price,this.amount)
				if(parseFloat(coupon.satisfy_price) > parseFloat(this.amount)){
					return uni.showToast({
						title:'未满足金额',
						icon:'none'
					})
				}
			}
			this.activeBtn = index
			uni.setStorageSync('coupon', coupon)
			this.scoupon = coupon
			uni.showToast({
				icon:'none',
				title:'使用成功'
			})
		},
		handelUse(index, coupon){
			this.useCoupon(index, coupon)
		},
		// 获取与毫秒数的转化比例（相差天数：1，相差小时数：2，相差分钟数：3，相差秒数：4）
		getDifferScale(value) {
		    var format
		    // 获取转化比（天数跟毫秒数的比例）
		    if (value === 1) {
		        format = parseFloat(24 * 60 * 60 * 1000)
		    } else if (value === 2) { // 获取转化比（小时数跟毫秒数的比例）
		        format = parseFloat(60 * 60 * 1000)
		    } else if (value === 3) { // 获取转化比（分钟数跟毫秒数的比例）
		        format = parseFloat(60 * 1000)
		    } else if (value === 4) { // 获取转化比（秒数跟毫秒数的比例）
		        format = parseFloat(1000)
		    }
		    return format
		},
		// firstDate: 2021-08-11 00:00:00
		// 获取两个日期的相差日期数(differ 相差天数：1、相差小时数：2、相差分钟数：3、相差秒数：4)
		getDifferDate(firstDate, secondDate, differ) {
		    // 1)将两个日期字符串转化为日期对象
		    let startDate = new Date(firstDate) 
			let endDate = new Date(secondDate)
		    // 2)计算两个日期相差的毫秒数
		    let msecNum = endDate.getTime() - startDate.getTime()
		    // 3)计算两个日期相差的天数
		    return Math.floor(msecNum / this.getDifferScale(differ))
		}
	}
}
</script>

<style lang="scss" scoped>
/* #ifdef H5 */
page {
	height: 100%;
}
/* #endif */

.gray{
	filter: grayscale(1);
}

.container {
	display: flex;
	flex-direction: column;
}

.exchange-box {
	flex-shrink: 0;
	height: 200rpx;
	background-color: #ffffff;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;

	.input-box {
		display: flex;
		align-items: stretch;
		width: 70%;
		flex-shrink: 0;
		input {
			flex: 1;
			height: 80rpx;
			border: 1rpx solid #eee;
			border-right: 0;
			border-radius: 8rpx 0 0 8rpx;
			padding: 20rpx;
			font-size: $font-size-base;
			color: $text-color-base;
		}
		button {
			border-radius: 0 8rpx 8rpx 0;
			display: flex;
			align-items: center;
		}
	}
}

.tabbar {
	flex-shrink: 0;
	width: 100%;
	height: 120rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	
	.tab {
		flex: 1;
		height: 100%;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		font-size: $font-size-base;
		color: $text-color-base;
		position: relative;
		
		.title {
			padding: 15rpx 0;
		}
		
		&.active {
			color: $color-primary;
			
			.title {
				border-bottom: 5rpx solid $color-primary;
			}
		}
	}
}

.bottom-box {
	height: 80rpx;
	flex-shrink: 0;
	.item {
		padding: 0 20rpx;
		position: relative;
		
		&::after {
			content: " ";
			border-right: 1rpx solid $text-color-assist;
			height: 100%;
			position: absolute;
			right: 0;
			top: 0;
			transform: scaleX(0.5) scaleY(0.8);
		}
		
		&:nth-last-child(1)::after {
			border-right: 0;
		}
	}
}

.coupon-list {
	height: calc(100vh - 80rpx);
	/* #ifdef H5 */
	height: calc(100vh - 80rpx - 120rpx - 200rpx - 44px);
	/* #endif */
}

.wrapper {
	display: flex;
	flex-direction: column;
	
	.coupon {
		display: flex;
		flex-direction: column;
		background-color: #FFFFFF;
		margin-bottom: 30rpx;
		padding: 0 30rpx;
		border-radius: 6rpx;
		box-shadow: 0 10rpx 10rpx -10rpx rgba(15, 15, 15, 0.1);
		position: relative;
		
		&::before {
			content: "";
			position: absolute;
			background-color: $bg-color;
			width: 30rpx;
			height: 30rpx;
			bottom: 65rpx;
			left: -15rpx;
			border-radius: 100%;
		}
		
		&::after {
			content: "";
			position: absolute;
			background-color: $bg-color;
			width: 30rpx;
			height: 30rpx;
			bottom: 65rpx;
			right: -15rpx;
			border-radius: 100%;
		}
		
		.detail {
			padding: 40rpx 0;
			position: relative;

		    &::after {
				content: '';
				position: absolute;
				left: 0;
				right: 0;
				bottom: 0;
				border-bottom: 1rpx dashed #c6c6c6;
				transform: scaleY(0.5);
			}
			
			.coupon-img {
				width: 150rpx;
				height: 150rpx;
				margin-right: 40rpx;
			}
			
			.use{
				display: flex;
				flex-direction: column;
				justify-content: flex-end;
				
				.btn{
					border-radius: 20rpx;
					color: #FFFFFF;
					background-color: #2b8a3e;
					text-align: center;
				}
				
				.activeBtn{
					background: #fcbc2c;
				}
				
				.info{
					color: #a4a4a4;
					width: 160rpx;
					height: 50rpx;
					text-align: center;
					margin-top: 20rpx;
				}
			}
		}
	}
}

.use-coupon-btn {
	width: 95%;
	border-radius: 50rem !important;
}

.none{
		margin-top: 50%;
		width: 200rpx;
		height: 200rpx;
		margin-left: 36%;
		image{
			width: 100%;
			height: 100%;
		}
	}
	
[v-cloak]{
		display:none!important
	}
</style>
